const express = require('express');
const router = express.Router();
const pool = require('../models/database.js');

router.post('/', async (req, res) => {
  const { user_id, pet_id } = req.body;
  if (!user_id || !pet_id) {
    return res.status(400).json({ code: 400, message: '缺少参数' });
  }

  try {
    await pool.query(
      'INSERT IGNORE INTO favorites (user_id, pet_id) VALUES (?, ?)',
      [user_id, pet_id]
    );
    res.json({ code: 200, message: '收藏成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 500, message: '收藏失败', error: err.message });
  }
});

router.delete('/', async (req, res) => {
  const { user_id, pet_id } = req.body;
  if (!user_id || !pet_id) {
    return res.status(400).json({ code: 400, message: '缺少参数' });
  }

  try {
    await pool.query(
      'DELETE FROM favorites WHERE user_id = ? AND pet_id = ?',
      [user_id, pet_id]
    );
    res.json({ code: 200, message: '取消收藏成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 500, message: '取消收藏失败', error: err.message });
  }
});

router.get('/:user_id', async (req, res) => {
  const { user_id } = req.params;

  try {
    const [rows] = await pool.query(
      `SELECT pet_list.* FROM favorites
       JOIN pet_list ON favorites.pet_id = pet_list.id
       WHERE favorites.user_id = ?`,
      [user_id]
    );
    res.json({ code: 200, message: '获取成功', data: rows });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 500, message: '获取收藏失败', error: err.message });
  }
});

router.delete('/batch', async (req, res) => {
  const { user_id, pet_ids } = req.body;
  if (!Array.isArray(pet_ids) || pet_ids.length === 0) {
    return res.json({ code: 400, message: 'pet_ids 必须是非空数组' });
  }
  try {
    const placeholders = pet_ids.map(() => '?').join(',');
    const params = [user_id, ...pet_ids];
    const [result] = await pool.query(
      `DELETE FROM favorites WHERE user_id = ? AND pet_id IN (${placeholders})`,
      params
    );
    res.json({ code: 200, message: '批量删除成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 500, message: '服务器错误', error: err.message });
  }
});

module.exports = router;